package cn.bonoon.kernel.support.services.handler;

import javax.persistence.EntityManager;

import cn.bonoon.kernel.events.OperateEvent;
import cn.bonoon.kernel.support.entities.EntityMovable;
import cn.bonoon.kernel.support.entities.EntityTree;

/**
 * 只有子节点才能向外移动
 * @author jackson
 *
 * @param <E>
 */
public class OperateTreeOutHandler<E extends EntityTree<E>> extends AbstractTreeMovableHandler<E>{
	private final String moveDownChild;
	public OperateTreeOutHandler(Class<E> entityClass) {
		super(entityClass);
		moveDownChild = "update " + entityClass.getName() + " set ordinal=ordinal+1 where ordinal>? and parent.id=?";
	}
	
	@Override
	public MultiOperateHandlerExecuter handler(EntityManager entityManager, OperateEvent event) {
		throw new RuntimeException("没有这种操作！");
	}
	
//	@Override
//	public Object handler(OperateSource service, OperateEvent event, Long id) {
//		EntityManager entityManager = service.getEntityManager();
//		E node = entityManager.find(entityClass, id);
//		E oldParent = node.getParent();
//		if(null != oldParent){
//			int ordinal = ((EntityMovable)oldParent).getOrdinal();
//			//oldParent节点下面的所有节点都向下移动一个位
//			entityManager.createQuery(moveDownChild)
//				.setParameter(1, ordinal)
//				.setParameter(2, oldParent.getId())
//				.executeUpdate();
//			entityManager.clear();
//			((EntityMovable)node).setOrdinal(ordinal + 1);
//			E newParent = oldParent.getParent();
//			if(null == newParent){
//				node.setParent(null);
//				node.setFullName(node.getName());
//				node.setXpath(node.getId() + "/");
//			}else{
//				node.setParent(newParent);
//				node.setFullName(newParent.getFullName() + node.getName());
//				node.setXpath(newParent.getXpath() + node.getId() + '/');
//				newParent.setSize(newParent.getSize() + 1);
//				entityManager.merge(newParent);
//			}
//			entityManager.merge(node);
//			oldParent.setSize(oldParent.getSize() - 1);
//			entityManager.merge(oldParent);
//		}
//		return null;
//	}
	
	@Override
	protected Object move(E node, EntityManager entityManager, E oldParent) {
		int ordinal = ((EntityMovable)oldParent).getOrdinal();
		//oldParent节点下面的所有节点都向下移动一个位
		entityManager.createQuery(moveDownChild)
			.setParameter(1, ordinal)
			.setParameter(2, oldParent.getId())
			.executeUpdate();
		entityManager.clear();
		((EntityMovable)node).setOrdinal(ordinal + 1);
		E newParent = oldParent.getParent();
		if(null == newParent){
			node.setParent(null);
			node.setFullName(node.getName());
			node.setXpath(node.getId() + "/");
		}else{
			node.setParent(newParent);
			node.setFullName(newParent.getFullName() + node.getName());
			node.setXpath(newParent.getXpath() + node.getId() + '/');
			newParent.setSize(newParent.getSize() + 1);
			entityManager.merge(newParent);
		}
		entityManager.merge(node);
		oldParent.setSize(oldParent.getSize() - 1);
		entityManager.merge(oldParent);
		return null;
	}
	
}
